package account

import (
	"context"
	"database/sql"
	"encoding/json"
	"errors"

	"user/internal/biz"
	"user/internal/model"
	"user/internal/svc"
	"user/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserInfoLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserInfoLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserInfoLogic {
	return &UserInfoLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserInfoLogic) UserInfo() (resp *types.UserInfoResp, err error) {
	// todo: add your logic here and delete this line
	userId, err := l.ctx.Value("userId").(json.Number).Int64()
	if err != nil {
		l.Logger.Error("userId get error:", err)
		return nil, biz.TokenError
	}
	if userId == 0 {
		return nil, biz.TokenError
	}
	userModel := model.NewCustomerEntityModel(l.svcCtx.Mysql)
	user, err := userModel.FindOne(l.ctx, userId)

	if err != nil && (errors.Is(err, model.ErrNotFound) || errors.Is(err, sql.ErrNoRows)) {
		l.Logger.Error("find user error:", err)
		return nil, biz.TokenError
	} else if err != nil {
		l.Logger.Error("find user error:", err)
		return nil, biz.DBError
	}

	return &types.UserInfoResp{
		Id:       user.Id,
		Username: user.Username,
	}, nil
}
